package com.example.flowable.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.flowable.model.Holiday;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.*;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping(value = "holiday")
public class HolidayController {
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private IdentityService identityService;

    /**
     * 部署请假流程
     */
    @RequestMapping(value = "deploy")
    @ResponseBody
    public String deploy() {
        //部署流程
        Deployment deployment = processEngine.getRepositoryService().createDeployment()
//                .name("请假流程")
                .addClasspathResource("flowable/holidayModel.bpmn20.xml")
                .deploy();
        return "部署成功.流程Id为：" + deployment.getId();
    }

//    /**
//     * 部署请假流程查询
//     */
//    @RequestMapping(value = "deploy/list")
//    @ResponseBody
//    public ResultDTO<List<ProcessDefinitionDTO>> deployList() {
//        List<ProcessDefinition> pdList = repositoryService.createProcessDefinitionQuery().list();
//        List<ProcessDefinitionDTO> resultList = new ArrayList<>();
//        for (ProcessDefinition pd:pdList) {
//            resultList.add(new ProcessDefinitionDTO(pd));
//        }
//        return new ResultDTO<List<ProcessDefinitionDTO>>().buildResultDTO(200, "sucess", resultList, resultList.size());
//    }

    /**
     * 发起请假流程
     */
    @RequestMapping(value = "add")
    @ResponseBody
    public String addHoliday(@RequestBody Holiday holiday) {
        //启动流程
        String jsonString = JSONObject.toJSONString(holiday);
        Map<String, Object> map = JSON.parseObject(jsonString,Map.class);
        // Authentication.setAuthenticatedUserId(holiday.getUserName());
        // 设置流程启动用户
        identityService.setAuthenticatedUserId(holiday.getUserName());
        // 设置下一审批组
        map.put("first","1");
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(holiday.getProcessDefinitionKey(),"businessKey111", map);
        // TODO 手动设置候选人
        // 查询task
        List<Task> taskList = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
        taskService.addCandidateUser(taskList.get(0).getId(), "7");
        return "请假审批流程开始.流程Id为：" + processInstance.getId();
    }

    /**
     * 获取审批管理列表
     */
    // @RequestMapping(value = "/list")
    // @ResponseBody
    // public Object list(String userId) {
    //     List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("managers").list();
    //     for (Task task : tasks) {
    //         System.out.println(task.toString());
    //     }
    //     return tasks.toArray().toString();
    // }

    /**
     * 查看任务信息
     */
    @RequestMapping(value = "show")
    @ResponseBody
    public Object show(String taskId){
        Map<String, Object> processVariables = taskService.getVariables(taskId);
        System.out.println(processVariables);
        return processVariables;
    }

    /**
     * 执行管理员任务
     */
    @RequestMapping(value = "/approve")
    @ResponseBody
    public Object approve(boolean approve, String taskId, String processInstanceId, String assignee){
        System.out.println(approve? "批准":"退回");
        HashMap<String, Object> map = new HashMap<>();
        map.put("holidayExeType", approve?"Y":"N");
        // if (!StringUtils.isEmpty(assignee)) {
        //     map.put("assignee", assignee);
        // }
        map.put("secend", "1");
        taskService.complete(taskId, map);
        // TODO 手动设置候选人
        // 查询task，不能直接用上面的taskId，因为完成之后taskId会变，secend差审批完就结束流程了，数据就到history中了，这里查询不到结果
        List<Task> taskList = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
        if (!taskList.isEmpty()) {
            taskService.addCandidateUser(taskList.get(0).getId(), "7");
        }
        return approve? "批准":"退回";
    }

    /**
     * 执行管理员任务
     */
    // @RequestMapping(value = "/execute")
    // @ResponseBody
    // public Object execute(){
    //     TaskService taskService = processEngine.getTaskService();
    //     List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("managers").list();
    //     System.out.println("You have " + tasks.size() + " tasks:");
    //     for (int i=0; i<tasks.size(); i++) {
    //         System.out.println((i+1) + ") " + tasks.get(i).getName());
    //     }
    //
    //     Task task = tasks.get(0);
    //     Map<String, Object> processVariables = taskService.getVariables(task.getId());
    //     System.out.println(processVariables.get("employee") + " 想请 " +
    //             processVariables.get("nrOfHolidays") + " 三天假. 同意？");
    //
    //     System.out.println("批准");
    //     HashMap<String, Object> map = new HashMap<>();
    //     map.put("approved", true);
    //     taskService.complete(task.getId(), map);
    //
    //     System.out.println("===== jack任务审批 ======");
    //     List<Task> tasks2 = taskService.createTaskQuery().taskCandidateOrAssigned("jack").list();
    //     System.out.println("jack have " + tasks2.size() + " tasks:");
    //     for (int i=0; i<tasks2.size(); i++) {
    //         System.out.println((i+1) + ") " + tasks2.get(i).getName());
    //     }
    //     taskService.complete(tasks2.get(0).getId(), map);
    //
    //     return "请假审批流程完成";
    // }
}
